package com.heima.behavior.service.impl;

import com.heima.behavior.config.CacheService;
import com.heima.behavior.service.ApArticleInfoService;
import com.heima.common.constants.user.UserRelationConstants;
import com.heima.model.behavior.dtos.ArticleInfoDto;
import com.heima.model.common.dtos.ResponseResult;
import com.heima.model.user.pojos.ApUser;
import com.heima.utils.threadlocal.AppThreadLocalUtils;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Service;

import java.util.HashMap;
import java.util.Map;

/**
 * @Description:
 * @Version: V1.0
 */
@Service
public class ApArticleInfoServiceImpl implements ApArticleInfoService {

    @Autowired
    CacheService cacheService;

    /**
     * 加载文章详情 数据回显
     * @param dto
     * @return
     */
    @Override
    public ResponseResult loadArticleBehavior(ArticleInfoDto dto) {
        //1 参数校验
        if (dto == null || dto.getArticleId() == null || dto.getAuthorApUserId() == null) {
            return ResponseResult.okResult();
        }

        // 用户登录
        ApUser user = AppThreadLocalUtils.getUser();
        if(user == null){
            return ResponseResult.okResult();
        }

        boolean isfollow = false, islike = false, isunlike = false, iscollection = false;

        //2 是否关注
        Double score1 = cacheService.zScore(UserRelationConstants.FOLLOW_LIST + user.getId(), dto.getAuthorApUserId().toString());
        if (score1 != null) {
            isfollow = true;
        }

        //3 是否收藏
        Double score2 = cacheService.zScore("BEHAVIOR:COLLECTION:" + user.getId(), dto.getArticleId() + ":" + 0);
        if (score2 != null) {
            iscollection = true;
        }

        //4 是否喜欢（点赞）
        Double score3 = cacheService.zScore(UserRelationConstants.BEHAVIOR_LIKE + user.getId(), dto.getArticleId().toString());
        if (score3 != null) {
            islike = true;
        }

        //5 是否不喜欢
        Double score4 = cacheService.zScore("BEHAVIOR:UNLIKE:" + user.getId().toString(), dto.getArticleId().toString());
        if (score4 != null) {
            isunlike = true;
        }


        //6 封装结果并返回
        Map<String, Boolean> map = new HashMap<>();
        map.put("isfollow", isfollow);
        map.put("iscollection", iscollection);
        map.put("islike", islike);
        map.put("isunlike", isunlike);

        return ResponseResult.okResult(map);
    }
}
